﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraBars;
using DevExpress.XtraGrid.Views.Grid;
using System.Diagnostics;
using DTO;
using BUS;
using System.Data.SqlClient;
namespace GPBenhLanh
{
    public partial class frmNhapTinCLS : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        public frmNhapTinCLS()
        {
            InitializeComponent();
            initControl(this);
          
        }

        public frmNhapTinCLS(int sel)
        {
            InitializeComponent();
            initControl(this);           
            select = sel;
        }
        private int select;     
        private static string strPathHinh = "";
        private bool firtLoad = true;//flag danh dau lau dau tien load len
        private int[] dataRes = new int[3];
        int maxSoXanh;
        public static string _strConnectPK;
        SqlConnection conpk;     
 
        /// <summary>
        /// get thong tin ket noi den database phKham
        /// </summary>
        public void getConnectStringPK()
        {
            string _sConnection = Uit.it_Conn.getConnectString("ConnectPhkham");
            _strConnectPK = axEnCrypt1.DeCrypt(_sConnection, Uit.it_Conn.getPasswordString());
        }
                
        public void CnPKham()
        {
            if (conpk == null || conpk.State == ConnectionState.Closed)
            {
                getConnectStringPK();
                conpk = new SqlConnection();
                conpk = Uit.it_Conn.getConnect(_strConnectPK);
            }            
        }

        public void getPathStrHinh()
        {
            string _sConnection = Uit.it_Conn.getConnectString("pathStrHinh");
            strPathHinh = axEnCrypt1.DeCrypt(_sConnection, Uit.it_Conn.getPasswordString());
        }

        private void initControl(Control ctrl)
        {
            // Bỏ qua điều kiểm trừ khi nó là TextBox.
            if (ctrl.Tag == "text")
            {
                ctrl.Text = "";
            }

            // Xử lý các điều kiểm một cách đệ quy.
            // Điều này cần thiết khi có một điều kiểm chứa nhiều 
            // điều kiểm khác (ví dụ, khi bạn sử dụng Panel, 
            // GroupBox, hoặc điều kiểm container nào khác).
            foreach (Control ctrlChild in ctrl.Controls)
            {
                initControl(ctrlChild);
            }
        }

        /// <summary>
        /// Get danh sach benh nhan theo loai benh nhan 
        /// va tinh trang da xac nhan hay chua
        /// </summary>
        /// <param name="nLoaiBN">
        /// 1: ngoai tru; 2: noi tru; 3: mien giam; 
        /// 4: chuong trinh; 5: ksk
        /// </param>
        /// <param name="bTinhTrang">1: da xac nhan; 2: chua xac nhan <param>
        /// <returns>dtKQ: sanh sach benh nhan</returns>
        private DataTable getDSBenhNhan(int nLoaiBN)
        {
            DataTable dtKQ = new DataTable();
            GetThongTinSearchDTO tt = new GetThongTinSearchDTO();
            tt.STuNgay = DateTime.Parse(datTuNgay.EditValue.ToString()).ToString("yyyy-MM-dd");
            tt.SDenNgay = DateTime.Parse(datDenNgay.EditValue.ToString()).ToString("yyyy-MM-dd");
            tt.SDichVu = "";//hensu.DVcode;
            //tt.SDonViTH = UserDTO.MaDonVi;//don vi cua user dang nhap vao he thong
           // tt.BTinhTrang = bTinhTrang;
            //int tinhTrang = int.Parse(radTinhTrang.EditValue.ToString());
           
            dtKQ = GetThongTinSearchBUS.GetThongTinSearch(tt, nLoaiBN, conpk);
           
            return dtKQ;
        }
        public DateTime addNgay()
        {
            DateTime datetime1 = DateTime.Today;//Old dateTime
            int dayDifference = (int)datetime1.DayOfWeek - (int)DayOfWeek.Saturday;
            if (dayDifference == 0) //datetime1 day is Saturday
            {
                //neu la thu 7 thi tu dong chuyen sang thu 2               
                datetime1 = datetime1.AddDays(2);//now its monday
            }
            else
            {
                //nho kha thu 7 thi tu dong add them 1 ngay
                datetime1 = datetime1.AddDays(1);
            }         
            return datetime1;
        }
             
        public TTXacNhanDTO setDataXacNhan()
        {            
            DataRow dr;
            dr = griddsBenhNhan.GetDataRow(griddsBenhNhan.FocusedRowHandle);
            TTXacNhanDTO xn = new TTXacNhanDTO();
            if (dr != null)
            {
                xn.SoHS = dr["sohs"].ToString();
                xn.SoBN = dr["sobn"].ToString();
                xn.SoNV = dr["sonhapvien"].ToString();
                xn.LoaiBN = int.Parse(graLoaiBenhNhan.EditValue.ToString());
                xn.ChatBP = txtChatBenhPham.Text;
                xn.NgayLayMau = DateTime.Parse(dr["ngaylaymau"].ToString());
                xn.ChuanDoan = txtChuanDoan.Text;
                xn.PPMo = int.Parse(comPPMo.EditValue.ToString());
                xn.Lanmo = 1;//nhớ kiểm tra isnumber cho chổ này
                if(txtLanMo.Text !="")
                    xn.Lanmo = int.Parse(txtLanMo.Text);

                xn.IDDViChiDinh = lblDVChiDinhID.Text;
                xn.Iddonviksk = 0;
                if (xn.LoaiBN == hensu.KSK)
                {
                    xn.Iddonviksk = int.Parse(lblDVChiDinhID.Text);
                }
                
                xn.TenDViChiDinh = txtDVChiDinh.Text;
                xn.PTVien = int.Parse(comptv.EditValue.ToString());
                if (dr["idbscd"].ToString() != "")
                    xn.IDBacSiCD = int.Parse(dr["idbscd"].ToString());
                else
                    xn.IDBacSiCD = 0;
           
                xn.IDDViGuiMau = comDVLayMau.EditValue.ToString();
                xn.CDate = DateTime.Parse(addNgay().ToString("yyyy-MM-dd")); 
                xn.DVuCode = dr["dvucode"].ToString();// hensu.DVcode;
                
            }
            return xn;
        }

        public string Right(string value, int length)
        {
            return value.Substring(value.Length - length);
        }
        public void TaoSo()
        {           
            int nam = int.Parse(Right(DateTime.Today.Year.ToString(), 2));
            int thang = DateTime.Today.Month;
            string sox = "";
            DataTable dtMax = TTXacNhanBUS.GetMax(hensu.SoXanh, nam, thang);
            if (dtMax != null)
            {
                if (dtMax.Rows.Count > 0)
                {
                    maxSoXanh = int.Parse(dtMax.Rows[0]["SoMax"].ToString()) + 1;
                    sox = dtMax.Rows[0]["Thang"].ToString()
                        + "." + maxSoXanh.ToString("0000");
                }
                else
                {
                    maxSoXanh = 1;
                    sox = thang.ToString("00") + "." + maxSoXanh.ToString("0000");
                }
            }
           
        }

        /// <summary>
        /// frmMain_Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmMain_Load(object sender, EventArgs e)
        {
            //set ngay thang nam
            datTuNgay.DateTime = DateTime.Now.Date;
            datDenNgay.DateTime = DateTime.Now.Date;

            comptv.Properties.DataSource = GetThongTinSearchBUS.SearchDSBacSiCD();
            comPPMo.Properties.DataSource = GetThongTinSearchBUS.SearchPPMo();
            comDVLayMau.Properties.DataSource = GetThongTinSearchBUS.SearchDonViGuiMau();
        
            radTinhTrang.SelectedIndex = 0;
            graLoaiBenhNhan.SelectedIndex = 0;

            radTinhTrang.EditValue = select;
            radTinhTrang.SelectedIndex = select-1;

            if (int.Parse(graLoaiBenhNhan.EditValue.ToString()) == 2)
            {
                griddsBenhNhan.Columns[0].Visible = false;
                griddsBenhNhan.Columns[1].Visible = false;
            }

            CnPKham();
            firtLoad = false;
        }

        private void btnKetQua_Click(object sender, EventArgs e)
        {
            if (txtSoHS.Text == "")
            {
                return;
            }
            TTXacNhanDTO xn = new TTXacNhanDTO();
            xn = setDataXacNhan();
            frmKetQuaCL frmKQ = new frmKetQuaCL(xn);
            frmKQ.thoatEven += new frmKetQuaCL.MyDelege2(frm_thoatEven);

            frmKQ.Show();
        }
        
        void frm_thoatEven(object sender, object data)
        {
            dataRes = (int[])data;
            if ((int)dataRes[0] == 1)
            {
                lblKQ1.Text = "true";
            }
            else if ((int)dataRes[0] == 2)
            {
                lblKQ2.Text = "true";
            }
            else
            {
                lblKQ1.Text = "false";
                lblKQ2.Text = "false";
            }
            if ((int)dataRes[1] == 1)
            {
                lblReload.Text = "true";
                ReLoadForm(sender);
            }
        }
        
        private void btnThoat_Click(object sender, EventArgs e)
        {
            //Uit.it_Conn.disConnect();
            this.Close();
        }

        private void btnTim_Click(object sender, EventArgs e)
        {
            DataTable dtKQ = new DataTable();
            CnPKham();

            int loaiBenh = (int)graLoaiBenhNhan.EditValue;
            //int tinhTrang = int.Parse(radTinhTrang.EditValue.ToString());
            //get danh sach benh nhan          
            dtKQ = getDSBenhNhan(loaiBenh);
            gridMain.DataSource = dtKQ;
            //
            chkHomSau.Checked = false;
            initControl(this);
            //btnXacNhan.Enabled = false;
        }

        bool checkXacNhan()
        {
            bool rs = true;
            if ((string)comDVLayMau.EditValue == "")
            {
                dxErrorProvider1.SetError(comDVLayMau, "Xin hãy chọn đơn vị gửi mẩu");
                return false;
            }
            else
            {
                dxErrorProvider1.ClearErrors();
                rs &= true;
            }
          
         
            return rs;
        }

        /// <summary>
        /// Ham tao so tieu ban cho cac chung tu theo quy uoc:
        /// GPB: Byy-xxxxx; PAP: Pyy-xxxxx; 
        /// FNA: Cyy-xxxxx; Cat Lanh: FSyy-xxxx;
        /// </summary>
        /// <param name="loaiSo">FS = 3;GPB = 4;PAP = 5;FNA = 6;</param>
        /// <param name="leng">Cat lanh = 4; GPB,PAP,FNA: 5</param>
        /// <returns>chuoi so tieu ban thoe quy uoc tren</returns>
        public string TaoSoTB(int loaiSo,int leng)
        {
            int soTB = 0;
            int nam = int.Parse(Right(DateTime.Today.Year.ToString(), 2));
            int thang = 0;
            string sox = "";
            string ssoTB = "";
            DataTable dtMax = TTXacNhanBUS.GetMax(loaiSo, nam, thang);
            if (dtMax != null)
            {
                if (dtMax.Rows.Count > 0)
                {
                    soTB = int.Parse(dtMax.Rows[0]["SoMax"].ToString()) + 1;
                    
                    if(leng==4)
                        ssoTB = soTB.ToString("0000");
                    else
                        ssoTB = soTB.ToString("00000");
                    sox = dtMax.Rows[0]["KyHieu"].ToString()
                        + dtMax.Rows[0]["Nam"].ToString()
                        +"-" + ssoTB;
                }
                else
                {
                    dtMax = TTXacNhanBUS.GetMax(loaiSo, nam-1, thang);
                    soTB = 1;
                    if (leng == 4)
                        ssoTB = soTB.ToString("0000");
                    else
                        ssoTB = soTB.ToString("00000");
                    sox = dtMax.Rows[0]["KyHieu"].ToString()
                        + nam + "-" + ssoTB;
                }
            }
            return sox;
        }

        //private void btnXacNhan_Click(object sender, EventArgs e)
        //{
        //    try
        //    {
        //         DataRow dr;
        //        dr = griddsBenhNhan.GetDataRow(griddsBenhNhan.FocusedRowHandle);
        //        if (dr == null)
        //        {
        //            return;
        //        }
        //        if (checkXacNhan() == false)
        //            return;
        //        TTXacNhanDTO xn = new TTXacNhanDTO();
        //        xn = setDataXacNhan();
        //        if (TTXacNhanBUS.InsertDaXacNhan(xn))
        //        {
        //            //update process
        //            int nLoaiBN = int.Parse(graLoaiBenhNhan.EditValue.ToString());
        //            TTXacNhanBUS.UpdateProcess(xn.SoBN, xn.SoHS, xn.SoNV
        //                                       , xn.DVuCode, true, nLoaiBN,conpk);                  
        //            //update so max lai    
        //            int nam = int.Parse(Right(DateTime.Today.Year.ToString(), 2));
        //            int thang = DateTime.Today.Month;
        //            int max =  int.Parse(Right(txtsoXanh.Text,hensu.LengSoCatLanh));
        //            //update max so xanh
        //            TTXacNhanBUS.UpdateMax(hensu.SoXanh, nam, thang, max);
                    
        //            //update max so tieu ban
        //            int loaiSTB = 0;
        //            loaiSTB = int.Parse(txtLoaiBenhPham.Text);
        //            int maxTB = 0;
        //            if (loaiSTB == 3)
        //            {
        //                maxTB = int.Parse(Right(txtSoTieuBan.Text, hensu.LengSoCatLanh));
        //            }
        //            else
        //            {
        //                maxTB = int.Parse(Right(txtSoTieuBan.Text, hensu.LengTeBao));
        //            }
        //            TTXacNhanBUS.UpdateMax(loaiSTB, nam, thang, maxTB);
        //        }
        //        txtSoTieuBan.Enabled = false;
        //        btnTim_Click(sender, e);
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.Message.ToString(), "Thông Báo");
        //    }
        //}

        private void btnBoXacNhan_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtSoHS.Text == "")
                {
                    return;
                }
                TTXacNhanDTO xn = new TTXacNhanDTO();
                xn = setDataXacNhan();

                if (TTXacNhanBUS.DeleteDaXacNhan(xn.SoHS, xn.SoBN))
                {
                    //update process
                    int nLoaiBN = int.Parse(graLoaiBenhNhan.EditValue.ToString());

                    TTXacNhanBUS.UpdateProcess(xn.SoBN, xn.SoHS, xn.SoNV
                                 , xn.DVuCode, false, nLoaiBN,conpk, UserDTO.MaDonVi);
                }
                btnTim_Click(sender, e);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Thông Báo", ex.Message.ToString());
            }
        }

        private void radTinhTrang_SelectedIndexChanged(object sender, EventArgs e)
        { 
            int tt = int.Parse(radTinhTrang.EditValue.ToString());
            switch (tt )
            {
            	case 1:
                    //btnXacNhan.Enabled = true;
                    comDVLayMau.Enabled = true;
                    
                    if (!firtLoad)
                    {
                        griddsBenhNhan.Columns[0].Visible = false;
                        griddsBenhNhan.Columns[1].Visible = false;
                    }
            		break;
                case 2:                  
                    //btnXacNhan.Enabled = false;
                    comDVLayMau.Enabled = false;
                   
                    if (!firtLoad)
                    {
                        griddsBenhNhan.Columns[0].Visible = true;
                        griddsBenhNhan.Columns[1].Visible = true;
                    }
            		break;
                case 3:
                    //btnXacNhan.Enabled = false;
                    comDVLayMau.Enabled = false;
                   
                    griddsBenhNhan.Columns["cloSoXanh"].Visible = true;
            		break;
            }            
           
            if (firtLoad == false)
                btnTim_Click(sender, e);
        }

        private void gridMain_Click(object sender, EventArgs e)
        {
            try
            {
                DataRow dr;
                dr = griddsBenhNhan.GetDataRow(griddsBenhNhan.FocusedRowHandle);
                if (dr != null)
                {
                    //set value to information panel
                    txtSoHS.Text = dr["sohs"].ToString();
                    txtSoBN.Text = dr["sobn"].ToString();
                    string dvcode = dr["dvucode"].ToString();
                    
                    txtDVChiDinh.Text = dr["tendonvi"].ToString();
                    txtHoTen.Text = dr["hoten"].ToString();
                    txtTuoi.Text = dr["namsinh"].ToString()
                                + "(" + dr["tuoi"].ToString() + " Tuổi)";
                    txtGioi.Text = dr["gioitinh"].ToString();
                    lblGioi.Text = dr["gioi"].ToString();
                    txtNamSinh.Text = dr["namsinh"].ToString()
                                + "(" + dr["tuoi"].ToString() + " Tuổi)";

                    txtSoNVien.Text = dr["sonhapvien"].ToString();
                    
                    txtdiachi.Text = dr["diachi"].ToString();
                    
                    datNgayLayMau.EditValue =
                        DateTime.Parse(dr["ngaylaymau"].ToString()).ToString("yyyy-MM-dd HH:mm");
                    lblngaygui.Text = dr["ngaynhan"].ToString();
                    lblngaylay.Text = dr["ngaylaymau"].ToString();
                    
                    comptv.EditValue = dr["ptvid"].ToString();
                    comPPMo.EditValue = dr["ppmoid"].ToString();
                    if (txtSoNVien.Text != "")
                    {
                        txtChuanDoan.Text = Uit.it_Font.VNIToUnicode(dr["chandoan"].ToString());
                    }
                    else
                    {
                        txtChuanDoan.Text = dr["chandoan"].ToString();
                    }
                    lblDVChiDinhID.Text = dr["madonvi"].ToString();

                    comDVLayMau.EditValue = dr["IDDViGuiMau"].ToString();

                    DataTable dtChiDinh =
                        GetThongTinSearchBUS.GetChiDinh(txtSoHS.Text, txtSoBN.Text, dvcode);

                    btnNhapTin.Enabled = true;
                    btnCapNhat.Enabled = false;
                    txtLanMo.Text = "0";

                    if (dtChiDinh != null)
                    { 
                        if (dtChiDinh.Rows.Count <= 0)
                            return;

                        btnCapNhat.Enabled = true;
                        btnNhapTin.Enabled = false;
                        comptv.EditValue = dtChiDinh.Rows[0]["PTVien"].ToString();
                        comPPMo.EditValue = dtChiDinh.Rows[0]["PPMo"].ToString();
                       
                        if (txtSoNVien.Text != "")
                        {
                            txtChuanDoan.Text = Uit.it_Font.VNIToUnicode(
                                           dtChiDinh.Rows[0]["ChuanDoan"].ToString());
                        }
                        else
                        {
                            txtChuanDoan.Text = dtChiDinh.Rows[0]["ChuanDoan"].ToString();
                        }
                        lblDVChiDinhID.Text = dtChiDinh.Rows[0]["DViChiDinh"].ToString();
                        comDVLayMau.EditValue = dtChiDinh.Rows[0]["IDDViGuiMau"].ToString();
                        txtLanMo.Text = dtChiDinh.Rows[0]["LanMo"].ToString();
                    }                    
                }              
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }
        }

        private void gridMain_KeyUp(object sender, KeyEventArgs e)
        {
            gridMain_Click( sender,  e);
        }

        private void ReLoadForm(object sender)
        {
            EventArgs e = new EventArgs ();
            if (lblReload.Text == "true")
            {
                btnTim_Click(sender, e);
            }
        }

        private void lblReload_TextChanged(object sender, EventArgs e)
        {
            if (lblReload.Text == "true")
            {
                btnTim_Click(sender, e);
            }
        }

        private void lblReload_Validated(object sender, EventArgs e)
        {
            if (lblReload.Text == "true")
            {
                btnTim_Click(sender, e);
            }
        }

        public static void DanhSoThuTu(RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator)
            {
                if (e.RowHandle < 0)
                    e.Info.DisplayText = "";
                else
                    e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
            else
            {
                e.Info.DisplayText = "STT";
            }
            e.Info.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
        }

        private void griddsBenhNhan_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            DanhSoThuTu(e);
        }

        private void barRpDaXacNhan_ItemClick(object sender, ItemClickEventArgs e)
        {
            frmThongKe frmTK = new frmThongKe();
            frmTK.ShowDialog();
        }

        private void btnedit_Click(object sender, EventArgs e)
        {
           
        }

        private void btnNhapTin_Click(object sender, EventArgs e)
        {
            try
            {
                DataRow dr;
                dr = griddsBenhNhan.GetDataRow(griddsBenhNhan.FocusedRowHandle);
                if (dr == null)
                {
                    return;
                }
                if (checkXacNhan() == false)
                    return;
                TTXacNhanDTO xn = new TTXacNhanDTO();
                xn = setDataXacNhan();
                if (TTXacNhanBUS.InsertChiDinh(xn))
                {
                    MessageBox.Show("Thông Báo","Lưu phiếu chỉ định thành công");
                }               
                btnTim_Click(sender, e);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }
        }

        private void btnCapNhat_Click(object sender, EventArgs e)
        {
            try
            {
                DataRow dr;
                dr = griddsBenhNhan.GetDataRow(griddsBenhNhan.FocusedRowHandle);
                if (dr == null)
                {
                    return;
                }
                if (checkXacNhan() == false)
                    return;
                TTXacNhanDTO xn = new TTXacNhanDTO();
                xn = setDataXacNhan();
                if (TTXacNhanBUS.UpdateChiDinh(xn))
                {
                    MessageBox.Show("Thông Báo", "Cập nhật thành công");
                }
                btnTim_Click(sender, e);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Thông Báo");
            }
        }

    }
}